import base64
import json
import time

import oss2
import requests
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework.response import Response

# Create your views here.
from rest_framework.views import APIView

from tools.baiduapi import bdapi, face
from tools.myjwt import mjwt
from login import models, serializers
from tools.myredis import r
from tools.sfl import f


# 钉钉登陆接口
# class DingTalkLogin(APIView):
#     def get(self, request):
#         from urllib.parse import quote
#         params = [
#             f"redirect_uri={quote('http://127.0.0.1:5173/huidiao/')}",
#             "response_type=code",
#             "client_id=dinges8uezk9e6kedgkq",
#             "scope=openid",
#             "prompt=consent",
#         ]
#         url = "https://login.dingtalk.com/oauth2/auth?" + ("&".join(params))
#         return Response({"url": url})
#
#
# # 回调接口
# class DingTalkCallback(APIView):
#     def post(self, request):
#         authcode = request.data.get('code')
#         data = {
#             "clientId": "dinges8uezk9e6kedgkq",
#             "clientSecret": "fxyWuZu_F5iC6qFki97WBI1agF6u7VvnUOJM5aqxgBGujhTH6vYe0B5EGwclA0bl",
#             "code": authcode,
#             "grantType": "authorization_code"
#         }
#
#         resp = requests.post('https://api.dingtalk.com/v1.0/oauth2/userAccessToken', json=data).json()
#         accessToken = resp.get('accessToken')
#
#         # 根据accessToken获取用户信息
#         headers = {"x-acs-dingtalk-access-token": accessToken}
#         resp = requests.get('https://api.dingtalk.com/v1.0/contact/users/me', headers=headers).json()
#
#         name = resp.get('nick')
#         uid = resp.get('openId')
#         moile = resp.get('mobile')
#         sfl = models.ThirdParty.objects.filter(uid=uid, party_type=3).first()
#
#         if not sfl:
#             user = models.Users.objects.filter(moile=moile).first()
#             if not user:
#                 user = models.Users.objects.create(
#                     username=name,
#                     moile=moile,
#                     password=moile,
#                     img="userimg/1.jpg"
#                 )
#             userinfo=models.ThirdParty.objects.create(
#                 user=user,
#                 party_type=3,
#                 uid=uid
#             )
#         else:
#             user = sfl.user
#
#         # 生成jwt token返回
#         payload = {"username": user.username, "userid": user.id, "exp": int(time.time() + 60 * 60 * 2)}
#         token = mjwt.jwt_encode(payload)
#         payload["exp"] = int(time.time() + 60 * 60 * 2 * 24)
#         refedshToken = mjwt.jwt_encode(payload)
#         return Response({"token": token, "refedshToken": refedshToken, "code": 200, "userid": user.id})

# 工厂模式钉钉登录
class DingLogin(APIView):
    def get(self, request, *args, **kwargs):
        type = self.kwargs.get('type')

        classname = f.create_f(type)
        url = classname.geturl()
        return Response({"url": url})

    def post(self, request, *args, **kwargs):
        code = self.request.data.get('code')
        type = self.kwargs.get('type')
        classname = f.create_f(type)
        data = classname.callback(code)
        return Response({"data": data})


# 用户详情
class User(APIView):
    def get(self, request):
        userid = request.GET.get('userid')
        print(userid)
        user = models.Users.objects.filter(id=userid).first()
        print(user.img, user.username, user.moile)
        return Response({"username": user.username, "img": user.img.url, "moile": user.moile})


#上传文件
from django.http import JsonResponse
from tools.ali_oss import aliyun_oss

@csrf_exempt
def upload_to_oss(request):
    """
    文件上传视图，将文件上传到阿里云oss
    """
    if request.method == 'POST' and request.FILES.get('file'):
        file_obj = request.FILES.get('file')#获取上传的文件对象
        file_name = f"idcard/{file_obj.name}"#设置文件名
        file_url=aliyun_oss.upload_file(file_obj, file_name)#上传文件到oss
        if file_url:
            return JsonResponse({"code": 200, "file_url": file_url})
        else:
            return JsonResponse({"code": 500, "message": "上传失败"})

    return JsonResponse({"code": 400, "message": "请求方式错误/无文件上传"})


class Idcard(APIView):
    def get(self, request):
        # 获取图片url
        url = request.GET.get('url')

        r.list_push('idcardlist', url)
        return Response({"code": 200,"msg": "上传成功","data":{"url": url}})



class BaiduUsermes(APIView):
    def get(self, request):
        url = request.GET.get('url')
        mes = r.get_str(url)
        code = 10010
        if mes:
            mes = json.loads(mes)
            code = 200
            r.str_del(url)
        # models.User_identity.objects.create(
        #     name=mes['name'],
        #     user=request.user, # 请求用户
        # )

        return Response({"code": code, "mes": mes})


#人脸识别
from rest_framework.parsers import MultiPartParser, FormParser

class FaceRecognitionView(APIView):
    # 允许处理文件上传
    # parser_classes = (MultiPartParser, FormParser)
    def post(self, request):

        img1_url = request.data.get('img1_url')  # OSS 图片 URL
        img2_base64 = request.data.get('img2')  # 视频截图 Base64 数据

        if not img1_url or not img2_base64:
            return Response({'code': 400, 'msg': '缺少图片数据'}, status=400)

        try:
            # 下载 OSS 图片
            response = requests.get(img1_url)

            if response.status_code != 200:
                return Response({'code': 400, 'msg': '无法获取 OSS 图片'}, status=400)

            img1_bytes = response.content  # OSS 图片字节数据
            img1_base64 = base64.b64encode(img1_bytes).decode("utf-8")

            # 调用人脸比对逻辑
            res = face.face(img1_base64, img2_base64)

            return Response({'code': 200, 'msg': res}, status=200)

        except Exception as e:
            return Response({'code': 500, 'msg': f'处理错误: {str(e)}'}, status=500)
